<template>
  <div class="home table-box">
    <ProTable ref="proTable" title="客户列表" highlight-current-row :columns="columns" :request-api="getUserList">
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'add'" type="primary" @click="openDrawer('新增')">新增客户</el-button>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button type="primary" link @click="openDrawer('查看', scope.row)">查看</el-button>
        <el-button type="primary" link @click="openDrawer('编辑', scope.row)">编辑</el-button>
        <el-button type="primary" link @click="openOrClose(scope.row)">{{
          scope.row.state !== customerStates[0].value ? '启用' : '禁用'
        }}</el-button>
        <el-button type="primary" link @click="deleteAccount(scope.row)">重置管理员密码</el-button>
      </template>
    </ProTable>
    <UserDrawer ref="drawerRef" />
  </div>
</template>
<script setup lang="ts">
import { useHandleData } from '@/hooks/useHandleData'
import { ResUserList } from './types'
import { customerTypes, customerStates } from './constant'
import UserDrawer from './components/UserDrawer.vue'
import { getUserList, addUser, editUser, resetCusPwdApi } from './apis'

// ProTable 实例
const proTable = ref()

// 表格配置项
const columns: any = [
  { prop: 'organizationName', label: '客户名称', search: { el: 'input' } },
  {
    prop: 'state',
    label: '客户状态',
    search: { el: 'select', props: { filterable: true } },
    enum: customerStates
  },
  {
    prop: 'organizationType',
    label: '客户类型',
    search: { el: 'select', props: { filterable: true } },
    enum: customerTypes
  },
  { prop: 'operation', label: '操作', fixed: 'right', width: 280 }
]

// 客户状态启用和禁用
const openOrClose = async (item) => {
  const [a, b] = customerStates
  const flag = item.state === a.value
  const params = { customerId: item.customerId, state: flag ? b.value : a.value }
  const msg = `${!flag ? '启用' : '禁用'}【${item.organizationName}】账号`
  await useHandleData(editUser, params, msg)
  // editUser({ customerId: item.customerId, state: flag ? b.value : a.value }).then(() => {
  //   ElMessage.success(!flag ? '启用成功' : '禁用成功')
  // })
  proTable.value?.getTableList()
}

// 重置管理员密码
const deleteAccount = async ({ customerId, organizationName }: { customerId: number; organizationName: string }) => {
  await useHandleData(resetCusPwdApi, { customerId }, `重置【${organizationName}】管理员密码`)
  proTable.value?.getTableList()
}

// 打开 drawer(新增、查看、编辑)
const drawerRef = ref<InstanceType<typeof UserDrawer> | null>(null)
const openDrawer = (title: string, row: Partial<ResUserList> = {}) => {
  const params = {
    title,
    isView: title === '查看',
    row: { ...row, citys: [row.provinceCode, row.cityCode, row.areaCode] },
    api: title === '新增' ? addUser : title === '编辑' ? editUser : undefined,
    getTableList: proTable.value?.getTableList
  }
  drawerRef.value?.acceptParams(params)
}
</script>
